<?php

namespace app\home\controller;

use app\home\model\Idfa724Model;
use app\home\model\Order;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use think\Db;
use think\helper\hash\Md5;
use think\Model;
use think\Request;
use think\response\Json;

class Pay800014 extends BasePay{

    const  secret = 'sk0fv70TS1Tsn1KVO21KaKqHVje8v8pS';
    const  appId = 'plpLq1uzi75qbzcs';
    const  gameid = '11000002';

    public function __construct()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
    }

    public function verifyToken(){
        $params = Request::instance()->param();
        mylog($params);
        $h = [
            'alg'=>'HS256',
            'typ'=>'JWT',
        ];
        $Header = base64_encode(json_encode($h));
       
        $d = [
            "iat"=>(int)$params['iat'],
            "exp"=>(int)$params['exp'],
            "nimoId"=>(int)$params['nimoId'],
            "appId"=>self::appId,
        ];
        $Payload = base64_encode(json_encode($d));
        $Payload = str_replace(array('+','/','='),array('-','_',''),$Payload);
        
        $sign = base64_encode(hash_hmac('sha256',$Header.'.'.$Payload, self::secret,true));
        $sign = str_replace(array('+','/','='),array('-','_',''),$sign);
        $token = $Header.'.'.$Payload.'.'.$sign;

        if($token == $params['token']){
            exit(json_encode(['code'=>1]));
        }
        exit(json_encode(['code'=>0]));


    }


    public function reportData(){
        $params = Request::instance()->param();
        mylog($params);
        $h = [
            'alg'=>'HS256',
            'typ'=>'JWT',
        ];
        $Header = base64_encode(json_encode($h));
        $iat = time();
        $exp = time()+600;
        $d = [
            "iat"=>$iat,
            "exp"=>$exp,
            "nimoId"=>$params['nimoId'],
            "appId"=>self::appId,
        ];
        $Payload = base64_encode(json_encode($d));
        $Payload = str_replace(array('+','/','='),array('-','_',''),$Payload);

        //TODO: 对方是C++ 秘钥需要替换
        $sign = base64_encode(hash_hmac('sha256',$Header.'.'.$Payload, self::secret,true));
        $sign = str_replace(array('+','/','='),array('-','_',''),$sign);

        $data = [
            'appId'=>self::appId,
            'nimoId'=>$params['nimoId'],
            'iat'=>$iat,
            'exp'=>$exp,
            'token'=>$Header.'.'.$Payload.'.'.$sign,
            'gameId'=>$params['gameId'],
            'event'=>$params['event'],
            'mid'=>$params['mid'],
            'serverId'=>$params['serverId'],
            'roleId'=>$params['roleId'],
            'roleLevel'=>$params['roleLevel'],
            'isFirst'=>$params['isFirst'],
            // 'isFirst'=>0,
        ];

        // var_dump($d);
        $res = http_build_query($data);
        mylog($res);
        $obj = $this->curl('https://open-live.nimo.tv/api/reportData',$res);
        mylog($params);
        exit($obj);
        // $params = Request::instance()->param();
        // mylog($params);
        // $res = http_build_query($params);
        // $obj = $this->curl('https://open-live.nimo.tv/api/reportData',$res);
        // mylog($params);
        // exit($obj);
    }

    public function order()
    {
        parent::order();

        $json_string = file_get_contents(env('PLATFORM.USD'));

        $config = json_decode($json_string, true);

        $usd  = $config[$this->order_array['goods_id']];

        if(empty($usd)){
            mylog('计费点对应的美元金额找不到');
            return false;
        }
         //保存第三方单号
         $tradeLog = (new \app\home\model\TradeLog)->where(['id'=>$this->order_array['id']])->find();
         if (empty($tradeLog)) {
             throw new \Exception('订单不存在');
         }
        $coin = (int)ceil($usd['Mpay'])*100;

        $tradeLog->dollPrice = $coin;
        //  $tradeLog->dollPriceType = 'US';
        $tradeLog->save();

        $payData = [
            "orderId" => $this->order_array['id'],
            "amount" => $coin,
            "ext" =>$this->order_array['id'],
        ];
        
        exit(json_encode(['code'=>1,'msg'=>'','data'=>$payData]));
    }

    


    public function notify()
    {
        parent::notify();
        $params = $this->params;
        mylog($params);
        try{
            $str = $params['nimoId'].$params['orderId'].$params['amount'].$params['udata'];
            //TODO: 对方是C++ 秘钥需要替换
            $sign = base64_encode(hash_hmac('sha256',$str, self::secret,true));
            $sign = str_replace(array('+','/','='),array('-','_',''),$sign);

            //验证签名
            if($sign != $params['sign']){
                throw new \Exception('sign false');
            }

            //保存第三方单号
            $tradeLog = (new \app\home\model\TradeLog)->where(['id'=>$params['udata']])->find();
            if (empty($tradeLog)) {
                throw new \Exception('订单不存在');
            }
            $tradeLog->transactionID = $params['orderId'];
            $tradeLog->save();

            if ($params['amount'] != $tradeLog['dollPrice']) {
                throw new \Exception('计费点不一致' . ' 传参:' .  $params['amount']  . ' 实际:' . $tradeLog['dollPrice']);
            }

            if ($tradeLog["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("800014 订单已经处理过了 订单id".$tradeLog['id']);
                exit('ok');
            }
            
            //发货
            $notifyService = new NotifyService();
            if($notifyService->notifyProcess($tradeLog) == false){
                throw new \Exception('notifyProcess false');
            }
            exit('ok');
        }catch (\Exception $exception){
            mylog('800014-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            exit('failed');
        }

    }

    

    
    /**
     * @param $url
     * @param null $body
     * @return bool|string
     * @throws Exception
     */
    protected function curl($url, $body = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: text/html"));
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  $body);
        //TODO 证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        
        curl_close($ch);
        mylog($response);
        return $response;

        
    }
   
}
